//
//  GMClientDetailViewController.m
//  GuardMan
//
//  Created by steven on 2017/2/24.
//  Copyright © 2017年 steven. All rights reserved.
//

#import "GMClientDetailViewController.h"
#import "GMButton.h"
#import "GMRedButton.h"
#import "GMDebtorDataController.h"
#import "NSDate+Utils.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <MBProgressHUD/MBProgressHUD.h>

#define kInfoTableViewCellIdentifier @"kInfoTableViewCellIdentifier"

enum {
    AnnotationViewControllerAnnotationTypeRed = 0,
    AnnotationViewControllerAnnotationTypeGreen,
    AnnotationViewControllerAnnotationTypePurple
};

@interface GMClientDetailViewController ()<MAMapViewDelegate, UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong)MAMapView *mapView;
@property (nonatomic, strong)XLFormDescriptor * form;
@property (nonatomic, strong)XLFormSectionDescriptor * section;
@property (nonatomic, strong)GMButton *paidButton;
@property (nonatomic, strong)GMRedButton *oweButton;
@property (nonatomic, strong)UIButton *delayButton;

@property (nonatomic, strong)UIBarButtonItem *editBarButtonItem;
@property (nonatomic, strong)UIBarButtonItem *cancelBarButtonItem;
@property (nonatomic, assign)BOOL editMode;

@property (nonatomic, strong) NSMutableArray *annotations;
@property (nonatomic, strong)GMDebtorDataController *debtorDataController;
@property (nonatomic, strong)GMDebtorModel *debtorModel;

@end

@implementation GMClientDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.editMode = NO;
    self.debtorDataController = [[GMDebtorDataController alloc] init];
    self.debtorModel = [[GMDebtorModel alloc] init];

    [self initializeForm];
    [self setupMainView];
    [self requestDetailDebtor];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.editBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(editBarButtonItemPressed)];
    self.cancelBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelBarButtonItemPressed)];

    self.navigationItem.rightBarButtonItem = self.editBarButtonItem;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    self.form.disabled = YES;
    [self.tableView reloadData];
}

#pragma mark - editBarButtonItemPressed
- (void)editBarButtonItemPressed {
    if (self.editMode) {
        // save action
        NSDictionary *formDict = [self.form formValues];
        NSDictionary *params = @{@"customerId": [NSString stringWithFormat:@"%ld", (long)self.debtorModel.id],
                @"name":formDict[@"name"],
                @"phone_number":formDict[@"phone"],
                @"pledge":formDict[@"pledge"]};

        [self.debtorDataController updateDebtorWithParams:params callback:^(NSString *error) {
            if (error == nil) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self renderSuccessView];
                });
            } else {
                [self showAlertMessage:error];
            }
        }];
    } else {
        self.editMode = YES;
        self.editBarButtonItem.title = @"保存";
        self.navigationItem.rightBarButtonItems = @[self.editBarButtonItem, self.cancelBarButtonItem];
        self.form.disabled = NO;
        [self.form formRowWithTag:@"endTime"].disabled = @YES;
        [self.tableView reloadData];
    }

}

#pragma mark - cancel barbutton item pressed
- (void)cancelBarButtonItemPressed {
    self.editMode = NO;
    self.editBarButtonItem.title = @"编辑";
    self.navigationItem.rightBarButtonItems = @[self.editBarButtonItem];

    [self.form formRowWithTag:@"name"].value = self.debtorModel.name;
    [self.form formRowWithTag:@"phone"].value = self.debtorModel.phoneNumber;
    [self.form formRowWithTag:@"pledge"].value = self.debtorModel.pledge;

    self.form.disabled = YES;
    [self.tableView reloadData];
}

#pragma mark - delay button pressed
- (void)delayButtonPressed {
    XLFormRowDescriptor * row = [self.form formRowWithTag:@"endTime"];
    if (row.isDisabled) {
        // enable end time now
        [self.delayButton setTitle:@"保存" forState:UIControlStateNormal];
        self.form.disabled = NO;
        [self.form formRowWithTag:@"name"].disabled = @YES;
        [self.form formRowWithTag:@"phone"].disabled = @YES;
        [self.form formRowWithTag:@"pledge"].disabled = @YES;
        [self.tableView reloadData];
    } else {
        NSDictionary *params = @{@"customerId": [NSString stringWithFormat:@"%ld", (long)self.debtorModel.id],
                @"end_time": [NSDate stringFromDate:row.value],
                @"status":@"delay"};

        [self.debtorDataController controlDebtorWithParams:params callback:^(NSString *error) {
            if (error == nil) {
                self.form.disabled = YES;
                row.cellConfig[@"textField.textColor"] = [UIColor grayColor];
                [self.delayButton setTitle:@"延期" forState:UIControlStateNormal];
                [self showAlertMessage:@"修改成功"];
            } else {
                [self showAlertMessage:error];
            }
        }];
    }
}

#pragma mark - paid button pressed
- (void)paidButtonPressed {
    NSDictionary *params = @{@"customerId": [NSString stringWithFormat:@"%ld", (long)self.debtorModel.id],
    @"status":@"complete"};

    [self.debtorDataController controlDebtorWithParams:params callback:^(NSString *error) {
        if (error == nil) {
            [self showAlertMessage:@"还款成功"];
        } else {
            [self showAlertMessage:error];
        }
    }];
}

#pragma mark - owe button pressed
- (void)oweButtonPressed {
    NSDictionary *params = @{@"customerId": [NSString stringWithFormat:@"%ld", (long)self.debtorModel.id],
            @"status":@"break"};
    [self.debtorDataController controlDebtorWithParams:params callback:^(NSString *error) {
        if (error == nil) {
            [self showAlertMessage:@"违约成功"];
        } else {
            [self showAlertMessage:error];
        }
    }];
}

- (void)requestDetailDebtor {
    NSDictionary *params = @{@"customerId": self.debtorId};
    [self.debtorDataController requestDetailDebtorWithParams:params callback:^(NSString *error) {
        if (error == nil) {
            [self renderSuccessView];
        } else {
            [self showAlertMessage:error];
        }
    }];
}

- (void)renderSuccessView {
    self.debtorModel = self.debtorDataController.debtorModel;
    self.annotations = [NSMutableArray array];

    CLLocationCoordinate2D coordinate = {self.debtorModel.lat, self.debtorModel.log};
    MAPointAnnotation *annotation = [[MAPointAnnotation alloc] init];
    annotation.coordinate = coordinate;
    [self.annotations addObject:annotation];

    [self.mapView addAnnotations:self.annotations];
    [self.mapView showAnnotations:self.annotations edgePadding:UIEdgeInsetsMake(20, 20, 20, 80) animated:YES];
    [self.mapView setZoomLevel:MAP_ZOOM_LEVEL animated:YES];
    [self.mapView setCenterCoordinate:coordinate];

    // form value
    [self.form formRowWithTag:@"name"].value = self.debtorModel.name;
    [self.form formRowWithTag:@"phone"].value = self.debtorModel.phoneNumber;
    [self.form formRowWithTag:@"pledge"].value = self.debtorModel.pledge;
    [self.form formRowWithTag:@"endTime"].value = [NSDate dateFromString: self.debtorModel.endTime];
    [self.tableView reloadData];
}

- (void)initializeForm {
    XLFormRowDescriptor * row;

    self.form = [XLFormDescriptor formDescriptorWithTitle:@"守卫详情"];

    // First section
    self.section = [XLFormSectionDescriptor formSectionWithTitle:@"基本信息"];
    [self.form addFormSection:self.section];

    // username
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"name" rowType:XLFormRowDescriptorTypeText title:@"姓名"];
    row.cellConfig[@"textField.textAlignment"] = @(NSTextAlignmentRight);
    [self.section addFormRow:row];

    // phone
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"phone" rowType:XLFormRowDescriptorTypeText title:@"手机号"];
    row.cellConfig[@"textField.textAlignment"] = @(NSTextAlignmentRight);
    [self.section addFormRow:row];

    // goods
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"pledge" rowType:XLFormRowDescriptorTypeText title:@"抵押物品"];
    row.cellConfig[@"textField.textAlignment"] = @(NSTextAlignmentRight);

    [self.section addFormRow:row];

    // Second Section
    self.section = [XLFormSectionDescriptor formSectionWithTitle:@"还款设置"];
    [self.form addFormSection:self.section];

    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"endTime" rowType:XLFormRowDescriptorTypeDateTime title:@"还款日期"];
    [row.cellConfig setObject:self.delayButton forKey:@"accessoryView"];

    [self.section addFormRow:row];

    self.form = self.form;
}

#pragma mark - set up main view
- (void)setupMainView {
    self.navigationItem.title = @"守卫详情";
    
    [self.view addSubview:self.mapView];
    [self.mapView autoPinEdgeToSuperviewEdge:ALEdgeTop];
    [self.mapView autoPinEdgeToSuperviewEdge:ALEdgeLeading];
    [self.mapView autoPinEdgeToSuperviewEdge:ALEdgeTrailing];
    [self.mapView autoSetDimension:ALDimensionHeight toSize:self.view.frame.size.height*0.26];
    
    [self.view addSubview:self.tableView];
    [self.tableView autoPinEdgeToSuperviewEdge:ALEdgeLeading];
    [self.tableView autoPinEdgeToSuperviewEdge:ALEdgeTrailing];
    [self.tableView autoPinEdgeToSuperviewEdge:ALEdgeBottom];
    [self.tableView autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.mapView];

    [self.view addSubview:self.paidButton];
    [self.view addSubview:self.oweButton];
    [self.view bringSubviewToFront:self.paidButton];
    [self.view bringSubviewToFront:self.oweButton];

    [self.paidButton autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:42];
    [self.paidButton autoPinEdgeToSuperviewEdge:ALEdgeLeading withInset:42];
    [self.paidButton autoSetDimensionsToSize:CGSizeMake(120, 40)];

    [self.oweButton autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:42];
    [self.oweButton autoPinEdgeToSuperviewEdge:ALEdgeTrailing withInset:42];
    [self.oweButton autoSetDimensionsToSize:CGSizeMake(120, 40)];
}

#pragma mark - map view
- (MAMapView *)mapView {
    if (!_mapView) {
        _mapView = [[MAMapView alloc] init];
        _mapView.delegate = self;
    }
    
    return _mapView;
}

- (GMButton *)paidButton {
    if (!_paidButton) {
        _paidButton = [[GMButton alloc] init];
        [_paidButton setTitle:@"已还款" forState:UIControlStateNormal];
        [_paidButton addTarget:self action:@selector(paidButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    }

    return _paidButton;
}

- (GMRedButton *)oweButton {
    if (!_oweButton) {
        _oweButton = [[GMRedButton alloc] init];
        [_oweButton setTitle:@"已违约" forState:UIControlStateNormal];
        [_oweButton addTarget:self action:@selector(oweButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    }

    return _oweButton;
}

- (UIButton *)delayButton {
    if (!_delayButton) {
        _delayButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 30)];
        [_delayButton.titleLabel setFont:[UIFont systemFontOfSize:14]];
        [_delayButton setTitle:@"延期" forState:UIControlStateNormal];
        [_delayButton.layer setCornerRadius:4];
        [_delayButton setBackgroundColor:BUTTON_ACTIVE_COLOR];
        [_delayButton addTarget:self action:@selector(delayButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    }

    return _delayButton;
}

#pragma mark - UITableViewDatasource
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 40;
    } else {
        return 18;
    }
}

#pragma mark - Map Delegate

/*!
 @brief 根据anntation生成对应的View
 @param mapView 地图View
 @param annotation 指定的标注
 @return 生成的标注View
 */
- (MAAnnotationView*)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation {
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *pointReuseIndetifier = @"pointReuseIndetifier";
        MAPinAnnotationView *annotationView = (MAPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndetifier];
        }
        
        annotationView.canShowCallout               = NO;
//        annotationView.animatesDrop                 = YES;
//        annotationView.draggable                    = YES;
//        annotationView.rightCalloutAccessoryView    = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
//        annotationView.pinColor                     = 0;
        annotationView.image = [UIImage imageNamed:@"client-guard-icon"];
        
        return annotationView;
    }
    
    return nil;
}

/*!
 @brief 当mapView新添加annotation views时调用此接口
 @param mapView 地图View
 @param views 新添加的annotation views
 */
- (void)mapView:(MAMapView *)mapView didAddAnnotationViews:(NSArray *)views {
    
}

/*!
 @brief 当选中一个annotation views时调用此接口
 @param mapView 地图View
 @param views 选中的annotation views
 */
- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view {
    
}

/*!
 @brief 当取消选中一个annotation views时调用此接口
 @param mapView 地图View
 @param views 取消选中的annotation views
 */
- (void)mapView:(MAMapView *)mapView didDeselectAnnotationView:(MAAnnotationView *)view {
    
}

/*!
 @brief 标注view的accessory view(必须继承自UIControl)被点击时调用此接口
 @param mapView 地图View
 @param annotationView callout所属的标注view
 @param control 对应的control
 */
- (void)mapView:(MAMapView *)mapView annotationView:(MAAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control {
    
}

/**
 *  标注view的calloutview整体点击时调用此接口
 *
 *  @param mapView 地图的view
 *  @param view calloutView所属的annotationView
 */
- (void)mapView:(MAMapView *)mapView didAnnotationViewCalloutTapped:(MAAnnotationView *)view {
    
}

/*!
 @brief 拖动annotation view时view的状态变化，ios3.2以后支持
 @param mapView 地图View
 @param view annotation view
 @param newState 新状态
 @param oldState 旧状态
 */
- (void)mapView:(MAMapView *)mapView annotationView:(MAAnnotationView *)view didChangeDragState:(MAAnnotationViewDragState)newState fromOldState:(MAAnnotationViewDragState)oldState {
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - show alert message
- (void)showAlertMessage:(NSString *)msg {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeText;
    hud.labelText = msg;
    // Configure for text only and offset down
    hud.margin = 10.f;
    hud.yOffset = Main_Screen_Height/2-98;
    hud.removeFromSuperViewOnHide = YES;

    [hud hide:YES afterDelay:MESSAGE_SHOW_TIME];
}

@end
